package net.alpcontrol.bi.bootstrap.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * Created by rickyjins on 2017/5/19.
 */
@Component
public class SpringContextUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    public static ApplicationContext getContext() {
        return applicationContext;
    }


    public static <T> T getBean(String name) {
        T t = null;
        try {
            t = (T) applicationContext.getBean(name);
        } catch (BeansException ex) {
//            ex.printStackTrace();
            AlpLogUtils.error(ex.getMessage());
        }
        return t;
    }

    public static <T> T getBean(Class<T> type) {
        T t = null;
        try {
            t = applicationContext.getBean(type);
        } catch (BeansException ex) {
            AlpLogUtils.error(ex.getMessage());
        }
        return t;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }
}
